package com.ugold.web.common.util;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

/**
 * Http工具
 * 
 * @author dingjian
 * @date 2018年10月30日
 */
public class HttpUtil {
	private static final String UNKNOWN = "unknown";

	// 代理请求头字段
	private static String headerIpFields[] = { "x-forwarded-for", "Proxy-Client-IP", "WL-Proxy-Client-IP",
			"HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR", "X-Real-IP" };

	/**
	 * 获取IP地址
	 * 
	 * @author dingjian
	 * @date 2018年10月30日
	 * @param request
	 * @return
	 */
	public static String getIpAddress(HttpServletRequest request) {
		if (request == null) {
			return null;
		}
		String ip = null;
		for (int i = 0; i < headerIpFields.length; i++) {
			if (isIpValid(ip) == false) {
				ip = request.getHeader(headerIpFields[i]);
			} else {
				return ip;
			}
		}
		if (isIpValid(ip) == false) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	/**
	 * 判断ip是否有效
	 *
	 * @param ip ip地址
	 * @return 是否有效
	 */
	private static boolean isIpValid(String ip) {
		return !(StringUtils.isBlank(ip) || UNKNOWN.equalsIgnoreCase(ip));
	}

}
